﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using ProjectManageSystemApi.Models;
using ProjectManageSystemApi.Services;
using ProjectManageSystemApi.Utilities;

namespace ProjectManageSystemApi.Controllers
{
    /// <summary>
    /// 人员权限接口
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [ApiExplorerSettings(GroupName = Grouping.GroupName_v1)]
    public class AuthController : Controller
    {
        readonly ILogger<AuthController> _logger;
        readonly IUserServices _user;
        readonly IRoleMenuServices _role;
        public AuthController(ILogger<AuthController> logger, IUserServices user, IRoleMenuServices role) 
        {
            _logger = logger;
            _user = user;
            _role = role;
        }

        /// <summary>
        /// 登录接口
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        [HttpPost, Route("Login")]
        public ApiResult Login([FromBody] Account account)
        {
            if (account == null 
                || account.UserName.IsNullOrEmpty() 
                || account.Password.IsNullOrEmpty()) 
            {
                return ApiResultStatus.Fail();
            }
            if (!_user.EnableByUserName(account.UserName))
            {
                return ApiResultStatus.Fail(ApiResultCodes.ACCOUNT_NOT_EXIST);
            }
            if (!_user.PasswordSame(account.UserName, account.Password))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PASSWORD_FAILED);
            }
            if (!_user.AllowedLoginType(account.UserName, account.Type)) 
            {
                return ApiResultStatus.Fail(ApiResultCodes.NOT_ALLOWED_LOGIN_PLATFORM);
            }
            var result = _user.GetToken(account.UserName);

            return ApiResultStatus.Success(result);
        }

        [HttpPost, Route("RefreshToken")]
        [AllowAnonymous]
        public ApiResult RefreshToken([FromBody] TokenRequest token)
        {
            if (token == null || string.IsNullOrWhiteSpace(token.AccountToken))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            var result = _user.RefreshToken(token.AccountToken);
            return ApiResultStatus.Success(result);
        }

        /// <summary>
        /// 获取用户信息和菜单，登录接口后调用
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("GetUserInfo")]
        [Authorize]
        public ApiResult GetUserInfo([FromHeader(Name = "Authorization")]string auth) 
        {
            string token = auth.ReplaceStr("Bearer ", "", true);
            if (string.IsNullOrWhiteSpace(token)) 
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            if (!_user.GetUserIdByToken(token, out long userId))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            UserMenuElementDto data = new UserMenuElementDto();
            data.Menus = _role.GetMenuByUserId(userId);
            data.Elements = _role.GetElementByUserId(userId);
            data.User = _user.GetUserByUserId(userId);
            return ApiResultStatus.Success(data);
        }



        /*
        
        /// <summary>
        /// 注册接口
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        [HttpPost, Route("Register")]
        public ApiResult Register([FromBody] Account account)
        {
            if (account == null
                || account.UserName.IsNullOrEmpty()
                || account.Password.IsNullOrEmpty())
            {
                return ApiResultStatus.Fail();
            }
            if (_user.ExistByUserName(account.UserName))
            {
                return ApiResultStatus.Fail(ApiResultCodes.DATA_EXIST);
            }
            if (!_user.Insert(account.UserName, account.Password))
            {
                return ApiResultStatus.Fail(ApiResultCodes.OPERATION_FAILED);
            }
            var result = _user.GetToken(account.UserName);
            return ApiResultStatus.Success(result);
        }
 
        /// <summary>
        /// 根据角色获取菜单
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("GetMenuByRoleId")]
        [Authorize]
        public ApiResult GetMenuByRoleId(long roleId) 
        {
            if (roleId == 0) 
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            var data = _role.GetAllMenuByRoleId(roleId);
            return ApiResultStatus.Success(data);
        }

        /// <summary>
        /// 修改角色菜单栏
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("UpdateMenuByRoleId")]
        [Authorize]
        public ApiResult UpdateMenuByRoleId(RoleMenuRequest roleMenu) 
        {
            if (roleMenu == null || roleMenu.RoleId == 0 || roleMenu.MeunIds.Count <= 0) 
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            if (_role.UpdateMenuByRoleId(roleMenu)) 
            {
                return ApiResultStatus.Fail(ApiResultCodes.OPERATION_FAILED);
            }
            return ApiResultStatus.Success();
        }
        */
    }
}
